package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * author by itheima
 *
 * @Date 2022/3/10
 * Description
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //  1. 校验参数
        // 评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论id不能为空");
        }
        Integer size = dto.getSize();
        if (size == null || size == 0) {
           dto.setSize(10);
        }
        if(dto.getMinDate()==null){
            dto.setMinDate(new Date());
        }
        //  2. 条件查询评论回复信息
        //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //   3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //3.1 如果未登录直接 返回评论回复列表
        if(user==null){
            return ResponseResult.okResult(apCommentRepays);
        }
        //3.2 如果登录，需要判断哪些回复点过赞
        List<String> commentRepayIds = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        //用户id = user.getId //  基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        Query likeRepayComment = Query.query(Criteria.where("authorId").is(user.getId())
                .and("commentRepayId").in(commentRepayIds));
        //获取点过赞的回复集合
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(likeRepayComment, ApCommentRepayLike.class);
       // 判断是否有集合是否为空和大于零
        if(apCommentRepayLikes!=null &&apCommentRepayLikes.size()>0){
           //得出点过赞的点赞Id
            List<String> likeIds = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId)
                    .collect(Collectors.toList());
            // 说明有点过赞的回复
            ArrayList<ApCommentRepayVO> apCommentVOList = new ArrayList<>();
           apCommentRepays.forEach(apCommentRepay -> {
               //  遍历 当前回复列表，将每一个回复信息 封装成 vo
               ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();

               BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
              //如果点赞的Ids中有回复id  设置实体类是点赞行为  //    判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
               if(likeIds.contains(apCommentRepay.getId())){
                   apCommentRepayVO.setOperation((short)0);
               }
               //把实体类存到集合中
               apCommentVOList.add(apCommentRepayVO);
           });
           return ResponseResult.okResult(apCommentVOList);
        }
       return ResponseResult.okResult(apCommentRepays);
    }

    @Autowired
    UserFeign userFeign;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //参数校验:
        //用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "需要先登录才能操作");
        }
        ResponseResult<ApUser> userResult = userFeign.findUserById(user.getId());
        if (userResult.getCode() != 0 || userResult.getData() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, userResult.getErrorMessage());
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);
        //更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //  1. 校验参数
        //  回复id不能为空   operation 必须 0 或 1
        // 校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "需要先登录");
        }
        //  校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //点赞操作
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId()));
        ApCommentRepayLike apLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        //    2. 如果是点赞  判断是否点过赞
        //  点过赞提示请勿重复点赞
        if (dto.getOperation() == 0) {
            if (apLike != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复点赞");
            }
            //  未点过赞， 保存点赞信息
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);
            // 并将回复信息的点赞数量字段+1
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
        } else {
            //  3. 如果是取消赞
            // 删除点赞信息
            if (apLike == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "您还没有点赞");
            }
            //更新评论的点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes() < 0 ? 0 : apCommentRepay.getLikes() - 1);
            mongoTemplate.save(apCommentRepay);
            //更新 APP评论信息点赞
            mongoTemplate.remove(query, ApCommentRepayLike.class);
        }
        //   并将回复信息的点赞数量字段
        //   4. 返回当前回复的最新点赞数量      数据的key:  likes
        HashMap<String, Object> map = new HashMap<>();
        map.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
